package com.example.administrator.hqq.activity.module;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.adapter.module.FlowLayoutAdapter;
import com.example.administrator.hqq.adapter.module.SearchModuleGridView;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.SearchModuleBean;
import com.example.administrator.hqq.bean.SearchTopicBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 搜索模块页面
 */
public class SearchModuleActivity extends MyActivity {

    @BindView(R.id.search)
    EditText search;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.search_bt)
    TextView searchBt;
    @BindView(R.id.delete_history_bt)
    AutoLinearLayout deleteHistoryBt;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout idFlowlayout;
    @BindView(R.id.grid)
    GridView grid;
    @BindView(R.id.history_auto)
    AutoLinearLayout historyAuto;
    @BindView(R.id.hot_flowlayout)
    TagFlowLayout hotFlowlayout;
    @BindView(R.id.empty)
    EmptyLayout empty;
    private List<String> strings;
    private FlowLayoutAdapter flowLayoutAdapter;
    private String TAG = this.getClass().getSimpleName();
    private List<SearchTopicBean.DataBean> data;
    private SearchModuleGridView searchModuleGridView;
    private List<String> topicIds;

    public enum SearchType {
        TOPIC, GROUP, FORUM
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_module);
        ButterKnife.bind(this);
        topicIds = (List<String>) getIntent().getSerializableExtra(LoongsConfig.topicIds);
        initview();
        initdata();
    }

    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.getSearchHistory())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.type, "TOPIC")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取搜索onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取搜索onResponse: " + response);
                Gson gson = new Gson();
                SearchModuleBean searchModuleBean = gson.fromJson(response, SearchModuleBean.class);
                if (searchModuleBean.getCode() == 200) {
                    strings.clear();
                    strings.addAll(searchModuleBean.getData());
                    flowLayoutAdapter.notifyDataChanged();
                }
            }
        });
    }

    /**
     * 搜索模块
     * @param keyWord
     */
    public void getSearchData(String keyWord) {
        AddModuleActivity.Type type = (AddModuleActivity.Type) getIntent().getSerializableExtra(LoongsConfig.type);
        String user_id="";
        switch (type){

            case REGISTER:
                break;
            case MODIFICATION:
                user_id=LoongsConfig.getUser_id();
                break;
        }

        OkHttpUtils.get().url(UrlFactory.getSearch())
                .addParams(LoongsConfig.user_id,user_id )
                .addParams(LoongsConfig.key_word, keyWord)
                .addParams(LoongsConfig.type, "TOPIC")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "搜索模块onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "搜索模块onResponse: " + response);
                Gson gson = new Gson();
                SearchTopicBean searchTopicBean = gson.fromJson(response, SearchTopicBean.class);
                if (searchTopicBean.getCode() == 200) {
                    initdata();
                    if (searchTopicBean.getData()==null||searchTopicBean.getData().size()<=0)
                    {
                        empty.showEmpty(R.drawable.empty_image,"搜索结果为空");
                    }else{
                        empty.hide();
                    }
                    historyAuto.setVisibility(View.GONE);
                    data.clear();
                    data.addAll(searchTopicBean.getData());
                    for (SearchTopicBean.DataBean datum : data) {
                        for (String topicId : topicIds) {
                            if (datum.getId().equals(topicId)) {
                                datum.setSelect(true);
                            }
                        }
                    }
                    searchModuleGridView.notifyDataSetChanged();
                }
            }
        });
    }

    public void start(Context context, String type) {
        Intent intent = new Intent(context, SearchModuleActivity.class);
        intent.putExtra(LoongsConfig.type, type);
    }

    private void initview() {
        data = new ArrayList<>();
        searchModuleGridView = new SearchModuleGridView(SearchModuleActivity.this, data);
        grid.setSelector(new ColorDrawable(Color.TRANSPARENT));
        grid.setAdapter(searchModuleGridView);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                data.get(i).setSelect(!data.get(i).isSelect());
                if (data.get(i).isSelect()) {
                    topicIds.add(data.get(i).getId());
                } else {
                    topicIds.remove(data.get(i).getId());
                }
                searchModuleGridView.notifyDataSetChanged();
            }
        });


        strings = new ArrayList<>();
        flowLayoutAdapter = new FlowLayoutAdapter(strings, this);
        idFlowlayout.setAdapter(flowLayoutAdapter);
        idFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                getSearchData(strings.get(position));
                return false;
            }
        });
        search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    search.setHint("");
                    search.setGravity(Gravity.CENTER_VERTICAL);
                } else {
                    if (TextUtils.isEmpty(search.getText().toString())) {
                        search.setHint("输入搜索关键字");
                        search.setGravity(Gravity.CENTER);
                    }
                }
            }
        });

    }

    @OnClick({R.id.search_bt, R.id.delete_history_bt, R.id.back, R.id.auto_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_bt:
                if (!TextUtils.isEmpty(search.getText())) {
                    getSearchData(search.getText().toString());
                }
                break;
            case R.id.delete_history_bt:
                deleteHistory();
                break;
            case R.id.back:
            case R.id.auto_back:
                Intent intent = new Intent();
                intent.putExtra(LoongsConfig.topicIds, (Serializable) topicIds);
                setResult(122, intent);
                finish();
                break;
        }
    }

    private void deleteHistory() {
        OkHttpUtils.get().url(UrlFactory.deleteSearchHistory())
                .addParams(LoongsConfig.user_id,LoongsConfig.getUser_id())
                .addParams(LoongsConfig.type,"TOPIC")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "删除历史记录onError: "+e.getMessage() );
                strings.clear();
                flowLayoutAdapter.notifyDataChanged();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "删除历史记录onResponse: "+response );
                strings.clear();
                flowLayoutAdapter.notifyDataChanged();
            }
        });
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(LoongsConfig.topicIds, (Serializable) topicIds);
        setResult(122, intent);
        finish();
    }
}
